package com.example.qsindusty.jmm_spline.ContralFragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.OrdeFragment.OrderData;
import com.example.qsindusty.jmm_spline.R;
import com.google.gson.Gson;
import com.yixin.ystartlibrary.base.BaseFragment;
import com.yixin.ystartlibrary.utils.DialogUtils;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.JsonUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.ToastUtils;
import com.yixin.ystartlibrary.widget.HintDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


public class MapFragment extends BaseFragment implements AMap.OnMarkerClickListener, AMap.InfoWindowAdapter, AMap.OnInfoWindowClickListener
        ,AMap.OnMapClickListener
        , AMap.OnCameraChangeListener,AMapLocationListener {

    @BindView(R.id.map)
    MapView mMapView;
    Unbinder unbinder;
    AMap aMap;
    @BindView(R.id.basicmap)
    RadioButton basicmap;
    @BindView(R.id.rsmap)
    RadioButton rsmap;
    @BindView(R.id.navimap)
    RadioButton navimap;
    @BindView(R.id.prienous)
    Button prienous;
    @BindView(R.id.next)
    Button next;
    @BindView(R.id.infowind)
    Button infowind;
    @BindView(R.id.lacation)
    Button lacation;
    private MarkerOptions markerOption;
    private MarkerOptions markerOption1;
    Marker marker;
    Marker locationmarker;//定位蓝点
    private List<LatLng> list;
    private List<Marker> markerList;

    int ssssss = 0;
    int crussitem =0;

    MyReceiver myReceiver ;
    Intent intent ;
    public MapFragment() {
        // Required empty public constructor
    }


    public static MapFragment newInstance() {
        MapFragment fragment = new MapFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.i("onCreate");
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("markmap1");
        intentFilter.addAction("markallmap1");
        getActivity().registerReceiver(myReceiver,intentFilter);
        intent = new Intent(getActivity(),ControlService.class);
        intent.putExtra(Config.flags,0);
        getActivity().startService(intent);
        LogUtils.i("onCreate1111");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_control, container, false);
        unbinder = ButterKnife.bind(this, view);
        mMapView.onCreate(savedInstanceState);
        list = new ArrayList<>();
        markerList = new ArrayList<>();
        initiview();
        initLocation();
        aMap.setInfoWindowAdapter(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnInfoWindowClickListener(this);
        aMap.setOnMapClickListener(this);
        return view;
    }

    private void initiview() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

    }

    /**
     * 在地图上添加marker
     */
    private void addMarkersToMap(LatLng latLng1,String title,String snippet,String rotate) {
        View view=    getLayoutInflater().inflate(R.layout.item_markopotion,null);
        TextView textView = view.findViewById(R.id.carnums);
        final ControlData.DataBean dataBean = JsonUtils.getModel(snippet, ControlData.DataBean.class);
        textView.setText(dataBean.getCPH());
        markerOption = new MarkerOptions()
                    .position(latLng1)
                    .icon(BitmapDescriptorFactory.fromView(view))
                    .title(title)
                    .snippet(snippet)
                    .rotateAngle(Float.parseFloat(rotate))//旋转角度
                    .draggable(true);

            marker = aMap.addMarker(markerOption);
            markerList.add(marker);


    }


    @Override
    protected int getContextView() {
        return 0;
    }

    @Override
    protected void init() {

    }

    @Override
    protected void initBundleData() {

    }


    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();

    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        mMapView.onDestroy();
        stopLocation();
        getActivity().unregisterReceiver(myReceiver);
        getActivity().stopService(intent);
    }

    @OnClick(R.id.basicmap)
    public void onBasicmapClicked() {
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        basicmap.setTextColor(getResources().getColor(R.color.white));
        rsmap.setTextColor(getResources().getColor(R.color.theme_color));
        navimap.setTextColor(getResources().getColor(R.color.theme_color));
    }

    @OnClick(R.id.rsmap)
    public void onRsmapClicked() {
        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
        basicmap.setTextColor(getResources().getColor(R.color.theme_color));
        rsmap.setTextColor(getResources().getColor(R.color.white));
        navimap.setTextColor(getResources().getColor(R.color.theme_color));

    }


    @OnClick(R.id.navimap)
    public void onViewClicked() {
        aMap.setMapType(AMap.MAP_TYPE_NAVI);
        basicmap.setTextColor(getResources().getColor(R.color.theme_color));
        rsmap.setTextColor(getResources().getColor(R.color.theme_color));
        navimap.setTextColor(getResources().getColor(R.color.white));

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (aMap != null) {
            jumpPoint(marker);
            if (marker.isInfoWindowShown()) {
                marker.hideInfoWindow();
            } else
                marker.showInfoWindow();
        }
            for (int i=0;i<markerList.size();i++){
                if (marker.getId().equals(markerList.get(i).getId())){
                    crussitem=i;
                }

            }

        return true;
    }

    /**
     * 点击效果
     * @param marker
     */
    public void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = aMap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * markerLatlng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }

    /**
     * Infowindow 信息窗口
     * @param marker
     * @return
     */
    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.custom_info_window, null);

        render(marker, infoWindow);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        View infoContent = getLayoutInflater().inflate(
                R.layout.custom_info_window, null);
        render(marker, infoContent);
        return infoContent;
    }

    public void render(final Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
            titleUi.setText(title);
        String snippet = marker.getSnippet();
        final ControlData.DataBean dataBean = JsonUtils.getModel(snippet, ControlData.DataBean.class);

        String curtime=dataBean.getGPS().getSJ();
        StringBuffer sb  = new StringBuffer();
        sb.append("车牌号："+dataBean.getCPH()).append("\n")
                .append("司机："+dataBean.getSJXM()).append("\n")
                .append("记录时间："+curtime).append("\n")
                .append("司机电话："+dataBean.getGPS().getLXDH()).append("\n")
                .append("位置："+dataBean.getGPS().getDZ());
        TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
            snippetUi.setText(sb.toString());
        TextView vhtext =view.findViewById(R.id.vhcion);
            vhtext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                showDialog(dataBean.getGPS().getLXDH(),dataBean.getGPS().getXM());

                }
            });
    }

    private  void  showDialog(final String phonenum, String name){
        final HintDialog hintDialog  = DialogUtils.createHintDialog(getActivity(), phonenum+":"+name);
        hintDialog.setTitleText("是否拨打");
        hintDialog.setConfirmText("拨打");
        hintDialog.setCancelText("取消");
        hintDialog.setConfirmListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phonenum));
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivity(intent);
                }
                if (hintDialog!=null&&hintDialog.isShowing())
                    hintDialog.dismiss();
            }
        });
        hintDialog.show();
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
        ToastUtils.showLongToast(getActivity(), marker.getTitle());
    }

    @OnClick({R.id.prienous, R.id.next, R.id.infowind, R.id.lacation})
    public void onViewClicked(View view) {
        Marker marker1 ;
        switch (view.getId()) {
            case R.id.prienous:
                if (markerList.size()==0||markerList==null){
                    ToastUtils.showLongToast(getActivity(),"还没有监控对象");
                    return;
                }

                LogUtils.i("cruitem==="+crussitem);
                marker1 = markerList.get(crussitem);
                ssssss=crussitem;
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1.getPosition()));

                crussitem=crussitem-1;
                if (crussitem<0){
                    crussitem=markerList.size()-1;

                }
              /*  crussitem  = s;
                marker1 = markerList.get(s);
                if (s==0){
                    prienous.setBackground(getResources().getDrawable(R.mipmap.map_left_hui));
                    prienous.setClickable(false);
                }else{
                    s=s-1;
                    prienous.setBackground(getResources().getDrawable(R.mipmap.map_left));
                    prienous.setClickable(true);

                }

                aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1.getPosition()));
                marker.hideInfoWindow();
                marker1.showInfoWindow();
                next.setBackground(getResources().getDrawable(R.mipmap.map_right));
                next.setClickable(true);*/
                break;
            case R.id.next:
                if (markerList.size()==0||markerList==null){
                    ToastUtils.showLongToast(getActivity(),"还没有监控对象");
                    return;
                }
                LogUtils.i("cruitem==="+crussitem);
                marker1 = markerList.get(crussitem);
                ssssss=crussitem;
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1.getPosition()));
                crussitem=crussitem+1;
                if (crussitem==markerList.size()){
                    crussitem=0;
                }

               /* crussitem =s ;
                marker1 = markerList.get(s);
                if (s==markerList.size()-1){
                    next.setBackground(getResources().getDrawable(R.mipmap.map_right_hui));
                    next.setClickable(false);
                } else{
                    s=s+1;
                    next.setBackground(getResources().getDrawable(R.mipmap.map_right));
                    next.setClickable(true);

                }
                marker1.getPosition();
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1.getPosition()));
                marker.hideInfoWindow();
                marker1.showInfoWindow();
                prienous.setBackground(getResources().getDrawable(R.mipmap.map_left));
                prienous.setClickable(true);*/
                break;
            case R.id.infowind:
                if (markerList.size()==0||markerList==null){
                    ToastUtils.showLongToast(getActivity(),"还没有监控对象");
                    return;
                }

                    marker1 = markerList.get(ssssss);
                    if (marker1.isInfoWindowShown())
                        marker1.hideInfoWindow();
                    else
                        marker1.showInfoWindow();


                break;
            case R.id.lacation:
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(locationmarker.getPosition()));
                break;

        }
    }

    /**
     * 初始化定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private void initLocation(){
        //初始化client
        locationClient = new AMapLocationClient(getActivity());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(this);
        startLocation();
    }
    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30*000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(60*000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void startLocation(){
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        // 停止定位
        locationClient.stopLocation();
    }
    private  void  clearMarker(){
        aMap.clear();
    }


    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if ( amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                LatLng latLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                //展示自定义定位小蓝点
                if(locationmarker == null) {
                    //首次定位
                    markerOption1 = new MarkerOptions()
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_icon))
                            .position(latLng)
                            .draggable(true);
                    locationmarker = aMap.addMarker(markerOption1);
                    //首次定位,选择移动到地图中心点并修改级别到15级
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
                } else {
                    markerOption1 = new MarkerOptions()
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.location_icon))
                            .position(latLng)
                            .draggable(true);
                    locationmarker.setPosition(latLng);
                    /*if(useMoveToLocationWithMapMode) {
                        //二次以后定位，使用sdk中没有的模式，让地图和小蓝点一起移动到中心点（类似导航锁车时的效果）
                        startMoveLocationAndMap(latLng);
                    } else {
                        startChangeLocation(latLng);
                    }*/

                }


            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }

    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (markerList.get(ssssss).isInfoWindowShown())
            markerList.get(ssssss).hideInfoWindow();
    }

    public  class  MyReceiver extends BroadcastReceiver {

        public MyReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtils.i("boardcast is gojin");
            if (TextUtils.equals(intent.getAction(),"markallmap1")){
                LogUtils.i("all");
                clearMarker();
                markerList.clear();
                locationmarker = aMap.addMarker(markerOption1);
                String tip= GeneralPreferencesUtils.getSharedPreference(getActivity(),Config.tip,null);
                ControlData controlData  = (ControlData) intent.getSerializableExtra(Config.data);
                for (ControlData.DataBean dataBean: controlData.getData()){
                    LogUtils.i(controlData.getData().toString());
                    if (dataBean.getGPS()!=null){
                        double v= Double.parseDouble(dataBean.getGPS().getWD());
                        double j= Double.parseDouble(dataBean.getGPS().getJD());
                        LatLng latLng2 = new LatLng(v,j);

                        Gson gson = new Gson();
                        String data= gson.toJson(dataBean, ControlData.DataBean.class);
                        addMarkersToMap(latLng2,dataBean.getORDERXH(),data,dataBean.getGPS().getFX());
                    }


                        }
                LogUtils.i("size:"+markerList.size());
                LogUtils.i("tip:"+tip);
                LogUtils.i("tip:"+crussitem);
                Marker mmarker = null;
                if (!TextUtils.isEmpty(tip)){
                    LogUtils.i("worininam1111111");
                    for (int i=0;i<markerList.size();i++){
                        LogUtils.i("worininam11222222");
                        LogUtils.i(markerList.get(i).getTitle()+"tile");
                        if (TextUtils.equals(markerList.get(i).getTitle(),tip)){
                            LogUtils.i("worininam");
                            mmarker=markerList.get(i);

                        }else{
                            mmarker=markerList.get(0);

                        }
                    }
                }else{
                  if (markerList.size()!=0)
                      if (crussitem>=markerList.size())
                          mmarker=markerList.get(0);
                  else
                        mmarker=markerList.get(crussitem);
                }
                if (tip!=null){
                    LogUtils.i("tip1:"+tip);
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(mmarker.getPosition()));
                    mmarker.showInfoWindow();
                    GeneralPreferencesUtils.setSharedPreference(getActivity(),Config.tip,null);
                }


/*
                if (mmarker!=null){
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(mmarker.getPosition()));
                    mmarker.showInfoWindow();
                    GeneralPreferencesUtils.setSharedPreference(getActivity(),Config.tip,null);
                        }
*/
            }

            else  if ((TextUtils.equals(intent.getAction(),"markmap1"))){
          final OrderData.DataBean dataBean = (OrderData.DataBean) intent.getSerializableExtra(Config.data);
                Marker mmarker = null;
                while (mmarker==null){

                    for (Marker marker :markerList){
                        if (TextUtils.equals(marker.getTitle(),dataBean.getXH())){
                            mmarker=marker;
                        }
                    }

                }
                if (mmarker!=null)
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(mmarker.getPosition()));
                    aMap.showIndoorMap(true);
            }

        }
    }

}
